package org.hbhk.hxl.gateway.services;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hbhk.hxl.gateway.boot.ApplicationContextUtil;
import org.hbhk.hxl.gateway.exception.RouteException;
import org.hbhk.hxl.gateway.model.Circuitbreaker;
import org.hbhk.hxl.gateway.model.HttpService;
import org.hbhk.hxl.gateway.model.Isolation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;

import com.google.common.util.concurrent.RateLimiter;

public class ServiceUtil implements InitializingBean {

	private static IGatewayService gatewayService;

	public static HttpService getHttpService(String url) {
		return gatewayService.getHttpService(url);
	}

	public static List<String> getDisableNode(String service) {
		List<String> httpNodes = gatewayService.getDisableNode(service);
		return httpNodes;
	}

	public static List<String> getNode(String url, String gray) {
		String app = gatewayService.getApp(url);
		if (StringUtils.isEmpty(app)) {
			throw new RouteException("服务应用不存在:" + url);
		}
		List<String> httpNodes = null;
		if ("1".equals(gray)) {
			httpNodes = gatewayService.getGrayNode(app);
		} else {
			httpNodes = gatewayService.getNode(app);
		}
		if (httpNodes != null) {
			List<String> disableNodes = gatewayService.getDisableNode(url);
			if (disableNodes != null && disableNodes.size() > 0) {
				httpNodes.removeAll(disableNodes);
			}
		} else {
			return null;
		}

		return httpNodes;
	}

	public static Circuitbreaker getBreaker(String url) {
		return gatewayService.getBreaker(url);
	}

	public static Isolation getIsolation(String url) {
		return gatewayService.getIsolation(url);
	}

	public static RateLimiter getRateLimit(String url) {
		return gatewayService.getRateLimit(url);
	}

	public static Integer getCachUrl(String url) {
		return gatewayService.getCacheUrl(url);
	}

	@Value("${gateway.data.type:mem}")
	private String type = "mem";

	@Override
	public void afterPropertiesSet() throws Exception {
		switch (type) {
		case "redis":
			gatewayService = (IGatewayService) ApplicationContextUtil.getApplicationContext()
					.getBean("hmsRedisService");
			break;
		default:
			gatewayService = (IGatewayService) ApplicationContextUtil.getApplicationContext()
					.getBean("hmsDefaultService");
			break;
		}
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getType() {
		return type;
	}
}
